<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="框架源码解析,">










<meta name="description" content="深入操作符操作符的实现原理?他是如何拦截事件，然后变换处理之后，最后传递到观察者手中的呢？ 这里依然以 map()为例,看看map背后到底做了什么: 这个例子更好理解: 12345678910111213141516171819202122232425262728293031323334353637383940414243//原始被观察者观察的是字符串//原始观察者观察到的是整数;//原始被观察者">
<meta name="keywords" content="框架源码解析">
<meta property="og:type" content="article">
<meta property="og:title" content="RxJava源码详解-操作符原理">
<meta property="og:url" content="https://zachaxy.github.io/2017/04/03/RxJava源码详解-操作符原理/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="深入操作符操作符的实现原理?他是如何拦截事件，然后变换处理之后，最后传递到观察者手中的呢？ 这里依然以 map()为例,看看map背后到底做了什么: 这个例子更好理解: 12345678910111213141516171819202122232425262728293031323334353637383940414243//原始被观察者观察的是字符串//原始观察者观察到的是整数;//原始被观察者">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-09-01T11:13:24.297Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="RxJava源码详解-操作符原理">
<meta name="twitter:description" content="深入操作符操作符的实现原理?他是如何拦截事件，然后变换处理之后，最后传递到观察者手中的呢？ 这里依然以 map()为例,看看map背后到底做了什么: 这个例子更好理解: 12345678910111213141516171819202122232425262728293031323334353637383940414243//原始被观察者观察的是字符串//原始观察者观察到的是整数;//原始被观察者">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/2017/04/03/RxJava源码详解-操作符原理/">





  <title>RxJava源码详解-操作符原理 | zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">


  <div id="posts" class="posts-expand">








  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/04/03/RxJava源码详解-操作符原理/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">RxJava源码详解-操作符原理</h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-04-03T09:23:28+08:00">
                2017-04-03
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  2,718
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">





        <h1 id="深入操作符"><a href="#深入操作符" class="headerlink" title="深入操作符"></a>深入操作符</h1><p>操作符的实现原理?他是如何拦截事件，然后变换处理之后，最后传递到观察者手中的呢？</p>
<p>这里依然以 map()为例,看看map背后到底做了什么:</p>
<p>这个例子更好理解:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//原始被观察者观察的是字符串</span></span><br><span class="line"><span class="comment">//原始观察者观察到的是整数;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//原始被观察者,真正负责发数据的;</span></span><br><span class="line">Observable&lt;String&gt; observable = Observable.create(<span class="keyword">new</span> Observable.OnSubscribe&lt;String&gt;() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">call</span><span class="params">(Subscriber&lt;? <span class="keyword">super</span> String&gt; subscriber)</span> </span>&#123;</span><br><span class="line">        subscriber.onNext(<span class="string">"1"</span>);</span><br><span class="line">        subscriber.onNext(<span class="string">"2"</span>);</span><br><span class="line">        subscriber.onNext(<span class="string">"3"</span>);</span><br><span class="line">        subscriber.onCompleted();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//代理被观察者,是由原始的被观察者衍生出来的;</span></span><br><span class="line">Observable&lt;Integer&gt; observableProxy = observable.map(<span class="keyword">new</span> Func1&lt;String, Integer&gt;() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">call</span><span class="params">(String s)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"转换工厂..."</span>);</span><br><span class="line">        <span class="keyword">return</span> Integer.valueOf(s);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//原始的观察者;</span></span><br><span class="line">Subscriber subscriber = <span class="keyword">new</span> Subscriber&lt;Integer&gt;() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCompleted</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onError</span><span class="params">(Throwable e)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onNext</span><span class="params">(Integer integer)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"我是真正的观察者-&gt; "</span> + integer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line">observableProxy.subscribe(subscriber);</span><br></pre></td></tr></table></figure>

<p>首先看一下这个<code>map</code>方法内部是如何实现的:首先明确一点:map方法返回的是一个代理被观察者,所以其实是原始观察者订阅了代理被观察者,这是整个前提!!!</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> &lt;R&gt; <span class="function">Observable&lt;R&gt; <span class="title">map</span><span class="params">(Func1&lt;? <span class="keyword">super</span> T, ? extends R&gt; func)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//创建了全新代理的的Observable，构造函数传入的参数是OnSubscribe</span></span><br><span class="line">        <span class="comment">//OnSubscribeMap显然是OnSubscribe的一个实现类，</span></span><br><span class="line">        <span class="comment">//也就是说，OnSubscribeMap需要实现call()方法</span></span><br><span class="line">        <span class="comment">//构造函数传入了原始的被观察者Observable对象,也就是说代理被观察者持有一个</span></span><br><span class="line">  		<span class="comment">//原始 被观察者的一个引用;</span></span><br><span class="line">        <span class="comment">//和一个开发者自己实现的Func1的实例,就是map的转化方法</span></span><br><span class="line">    <span class="keyword">return</span> create(<span class="keyword">new</span> OnSubscribeMap&lt;T, R&gt;(<span class="keyword">this</span>, func)); <span class="comment">//this是原始被观察者;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>因为map 实现的功能是 将 a 转换为 b,a/b均是被观察者,所以map中又创建了一个 Observable 的对象;</p>
<p>map背后究竟做了什么?</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//牢牢记住,这个OnSubscribeMap本质上还是一个OnSubscribe对象,用来创建被观察者时传入的,这是整个前提!</span></span><br><span class="line"><span class="comment">//上面也看到了 map()方法中又创建了一个新的被观察者(代理被观察者)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">OnSubscribeMap</span>&lt;<span class="title">T</span>, <span class="title">R</span>&gt; <span class="keyword">implements</span> <span class="title">OnSubscribe</span>&lt;<span class="title">R</span>&gt; </span>&#123;</span><br><span class="line">    <span class="comment">//用于保存原始的Observable对象</span></span><br><span class="line">    <span class="keyword">final</span> Observable&lt;T&gt; source;</span><br><span class="line">    <span class="comment">//还有我们传入的那个Func1的实例,func1中提供了转换  a-&gt;b 方法; 是通过 Func1 中的 T call()方法实现的</span></span><br><span class="line">    <span class="keyword">final</span> Func1&lt;? <span class="keyword">super</span> T, ? extends R&gt; transformer;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">OnSubscribeMap</span><span class="params">(Observable&lt;T&gt; source, Func1&lt;? <span class="keyword">super</span> T, ? extends R&gt; transformer)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.source = source;</span><br><span class="line">        <span class="keyword">this</span>.transformer = transformer;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//实现了call方法，我们知道call方法传入的Subscriber</span></span><br><span class="line">  	<span class="comment">//mad,这个call 方法一定要和 Func1 中的 转换方法 call 区分开,这个 call 方法是用来发送事件的;</span></span><br><span class="line">    <span class="comment">// 这个代理的被观察者的call方法有什么用呢?还用问,被观察者没有call方法还玩个毛.</span></span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line"> <span class="comment">//和原来不同的是,这个call中并不是调用观察者的next()方法.而是产生一个新的观察者=&gt;代理观察者;</span></span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line">    <span class="comment">//然后产生一个新的的订阅关系=&gt;原始被观察者和代理观察者的订阅</span></span><br><span class="line">    <span class="comment">//就是订阅之后，外部传入真实的的观察者,观察者什么时候传进来的?答:最终就是这个代理被观察者订阅的原始的观察者啊,所以这个o就是原始观察者;</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">call</span><span class="params">(<span class="keyword">final</span> Subscriber&lt;? <span class="keyword">super</span> R&gt; o)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// o 是原始观察者.</span></span><br><span class="line">        <span class="comment">//把外部传入的真实观察者传入到MapSubscriber，构造一个 代理的观察者</span></span><br><span class="line">        <span class="comment">//parent是代理观察者;</span></span><br><span class="line">        MapSubscriber&lt;T, R&gt; parent = <span class="keyword">new</span> MapSubscriber&lt;T, R&gt;(o, transformer);</span><br><span class="line">      </span><br><span class="line">       <span class="comment">//给原始的观察者添加一个订阅;改了啊,改了,原始的观察者现在订阅代理观察者了,mad;</span></span><br><span class="line">       <span class="comment">//其实下面这句话可以忽略,没啥实际意义;</span></span><br><span class="line">        o.add(parent);</span><br><span class="line">        <span class="comment">//让外部的Observable去订阅这个代理的观察者</span></span><br><span class="line">      <span class="comment">//其实是: 代理观察者去订阅原始的观察者</span></span><br><span class="line">        source.unsafeSubscribe(parent);  <span class="comment">//!!!!核心在这一步,正是由于这一步,原始被观察者就发送数据了;</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//Subscriber的子类，用于构造一个代理的观察者</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">MapSubscriber</span>&lt;<span class="title">T</span>, <span class="title">R</span>&gt; <span class="keyword">extends</span> <span class="title">Subscriber</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">        <span class="comment">//这个Subscriber保存了原始的观察者</span></span><br><span class="line">        <span class="keyword">final</span> Subscriber&lt;? <span class="keyword">super</span> R&gt; actual;</span><br><span class="line">        </span><br><span class="line">      <span class="comment">//我们自己在外部自己定义的Func1,转换方法 a-&gt;b</span></span><br><span class="line">        <span class="keyword">final</span> Func1&lt;? <span class="keyword">super</span> T, ? extends R&gt; mapper;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">boolean</span> done;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">MapSubscriber</span><span class="params">(Subscriber&lt;? <span class="keyword">super</span> R&gt; actual, Func1&lt;? <span class="keyword">super</span> T, ? extends R&gt; mapper)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.actual = actual; <span class="comment">//原始观察者;</span></span><br><span class="line">            <span class="keyword">this</span>.mapper = mapper;  <span class="comment">//转换方法;</span></span><br><span class="line">        &#125;</span><br><span class="line">      </span><br><span class="line">      </span><br><span class="line">        <span class="comment">//原始的Observable发送的onNext()等事件</span></span><br><span class="line">        <span class="comment">//都会首先传递到代理观察者这里?为什么,在哪里实现的?</span></span><br><span class="line">      <span class="comment">//其实并没有什么所谓的传递,事件只是一个变量,直接用就可以了;</span></span><br><span class="line">      <span class="comment">//看上面代理被观察者中的call方法,最后不是将 原始被观察者 与 代理观察者绑定了嘛...</span></span><br><span class="line">      <span class="comment">//有道理 √</span></span><br><span class="line">      <span class="comment">//本来啊,是被观察者</span></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onNext</span><span class="params">(T t)</span> </span>&#123;</span><br><span class="line">            R result;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="comment">//mapper其实就是开发者自己创建的Func1，</span></span><br><span class="line">                <span class="comment">//call()开始变换数据</span></span><br><span class="line">              <span class="comment">//t是事件,事件只是一个变量,直接用就可以,并不存在事件的传递;</span></span><br><span class="line">              <span class="comment">//这里只是将一个变量转换为另一种类型的变量;</span></span><br><span class="line">                result = mapper.call(t);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">                Exceptions.throwIfFatal(ex);</span><br><span class="line">                unsubscribe();</span><br><span class="line">                onError(OnErrorThrowable.addValueAsLastCause(ex, t));</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">//调用真实的观察者的onNext()</span></span><br><span class="line">            <span class="comment">//从而在变换数据之后，把数据送到真实的观察者手中</span></span><br><span class="line">            actual.onNext(result);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//onError()方法也是一样</span></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onError</span><span class="params">(Throwable e)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">if</span> (done) &#123;</span><br><span class="line">                RxJavaHooks.onError(e);</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            done = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">            actual.onError(e);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCompleted</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">if</span> (done) &#123;</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            actual.onCompleted();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setProducer</span><span class="params">(Producer p)</span> </span>&#123;</span><br><span class="line">            actual.setProducer(p);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>代理被观察者存在的意义:之前我在想,如果经过map转换的话,只是需要一个代理观察者就好了,为什么还需要一个代理被观察者,其实代理被观察者在这里有两个使命:</p>
<ul>
<li>并不是所有的代码都是按照流式一下写下来的,可能是分别创建观察者,被观察者,然后订阅,这个时候map的转换需要产生一个代理被观察者</li>
<li>代理被观察者与原始观察者进行订阅,代理被观察者中的call方法是先执行的,那么它的call()方法内部实现了什么呢?就是原始被观察者和代理被观察者的订阅,因为代理被观察者是没有数据源的,只有在这里call()中进行订阅,原始被观察者才会发出数据,给代理被观察者用func1转换方法处理,处理后再发送原始观察者;</li>
</ul>
<ol>
<li><p>问题1:这个代理观察者的观察者参数是什么时候传进来的?</p>
<p>答:不要心急,记住总的原则是:观察者是在订阅的时候传入进来的.我们可以这样理解,本来我们创建被观察者和观察者,然后订阅.现在多了一个 map 操作,经过map操作后,被观察者就变了,变成了这个代理被观察者,这时候我们忘掉原始的观察者吧.原始的观察者只负责产生原始的事件源,何况这个代理被观察者中还持有原始被观察者的引用.那么在这个代理被观察者的call方法中其实是使用原始被观察者的call发原始数据,只不过发之前先不给观察者,而是自己调用func1来把事件转换一下;</p>
</li>
</ol>
<p>map(Func1 func1);</p>
<p>首先我们看在使用map时,需要传入一个 Func1 实例,其实 Func1 是一个接口,需要实现的方法是一个 call()方法,正是靠这个call 方法实现的转换;</p>
<p>接下来看 map 内部是怎么实现的,其创建了一个 Observable 实例并返回;这也很好理解,进行了 map 转换后还是一个被观察的对象;,</p>
<p>return create(new OnSubscribeMap&lt;T, R&gt;(this, func));</p>
<p>跟进去这个创建的流程中,前面也分析了创建一个 Observable 对象不能 new,而是使用一个 create()方法,并传入一个 OnSubscribe 的实例;同理 map 中创建的 Observable 对象也一样,只是这个传入的是 OnSubscribeMap 对象,这是 OnSubscribe 接口的一个实现类, OnSubscribeMap 需要两个参数,第一个参数是原始的被观察着,第二个参数是用来转换的 Func1 对象,之前也讲过,每个 被观察者中都持有一个 OnSubscribe,这个接口要求实现一个 call 方法,这个call方法是用来触发事件开始执行的,我们用了map新键的一个被观察者,对象被转换后,也需要一个新的触发机制,就在这个call中实现.</p>
<p>接下来看一下 OnSubscribeMap 中时如何实现 call() 方法的,在这个call方法中传入的是观察者,嗯,没错,传入的是观察者,这里新键了一个观察者,我们称之为代理观察者,</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>这里面一共涉及到了四个对象</p>
<ul>
<li>被观察者</li>
<li>代理被观察者</li>
<li>观察者</li>
<li>代理观察者</li>
</ul>
<ol>
<li><p>被观察者通过 map 转换后产生了新的 代理被观察者,并持有原始被观察者的引用与转换的方法</p>
</li>
<li><p>(map方法产生的)代理被观察者 与 原始观察者产生订阅(明面上的,你看得到)</p>
</li>
<li><p>通过上一步的订阅,代理被观察者就持有了原始观察者的引用</p>
</li>
<li><p>代理被观察者的call方法中创建一个代理观察者</p>
</li>
<li><p>代理观察者与原始被观察者进行订阅</p>
</li>
<li><p>通过上一步的订阅,原始观察者发送消息给 代理观察者,发来的是 String</p>
</li>
<li><p>代理观察者是代理被观察者的内部类,自然也可以访问代理被观察者的属性—转换方法</p>
</li>
<li><p>代理观察者在其<code>onNext()</code>方法中获取到<code>String</code>,然后通过转换方法将 String 装换为 int</p>
</li>
<li><p>代理观察者通过原始观察者的引用,将 int传给观察者(其实这时的代理观察者又有点被观察者的意思,它调用了原始观察者的 onNext(int) 方法)</p>
</li>
<li><p>整个流程结束;</p>
</li>
</ol>


    </div>









      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zachaxy
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zachaxy.github.io/2017/04/03/RxJava源码详解-操作符原理/" title="RxJava源码详解-操作符原理">https://zachaxy.github.io/2017/04/03/RxJava源码详解-操作符原理/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>


    <footer class="post-footer">

        <div class="post-tags">

            <a href="/tags/框架源码解析/" rel="tag"># 框架源码解析</a>

        </div>







        <div class="post-nav">
          <div class="post-nav-next post-nav-item">

              <a href="/2017/04/03/RxJava源码详解-订阅原理/" rel="next" title="RxJava源码详解-订阅原理">
                <i class="fa fa-chevron-left"></i> RxJava源码详解-订阅原理
              </a>

          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">

              <a href="/2017/04/03/RxJava源码详解-线程切换原理/" rel="prev" title="RxJava源码详解-线程切换原理">
                RxJava源码详解-线程切换原理 <i class="fa fa-chevron-right"></i>
              </a>

          </div>
        </div>




    </footer>
  </div>



  </article>



    <div class="post-spread">

    </div>
  </div>


          </div>









        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">




        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>


      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>


      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">






              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#深入操作符"><span class="nav-number">1.</span> <span class="nav-text">深入操作符</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">1.1.</span> <span class="nav-text">总结</span></a></li></ol></li></ol></div>


          </div>
        </section>
      <!--/noindex-->




    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>







  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>






  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
